/**
 * 
 */
package bot;

import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.HashMap;

import trigger.*;

import messagetype.*;


/**
 * @author Philip
 *
 */
public class IrcBot extends IrcUser {
	public static final String CHANNEL_MODE = "324";
	public static final String END_OF_MOTD = "376";
	public static final String NAMES_LIST = "353";
	public static final String NICKNAME_ALREADY_IN_USE = "433";
	
	
	private Client client;
	private ArrayList<Trigger> triggerList;
	private InputLineSegmenter lineSegmenter;
	private HashMap<String, MessageType> map = new HashMap<String, MessageType>();

	public IrcBot(String nickName, String fullName, String authName, String autoJoinChannels, Client client, ArrayList<Trigger> triggerList) {
		super(nickName, fullName, authName);
		this.client = client;
		this.triggerList = triggerList;
		
		lineSegmenter = new InputLineSegmenter();

//		map.put("JOIN", new JoinMessageType());
		map.put("PING", new PongMessageType());
		map.put("NICK", new NickMessageType());
		map.put(END_OF_MOTD, new EndOfMOTDMessage(autoJoinChannels));
	}
	
	public void connect() {
		client.connect();

		client.write("NICK " + nickName);
		client.write("USER " + nickName + " ignored " + client.getServer() + " :" + fullName);

		while (client.isConnected()) {
			String inputLine = null;
			try {
				inputLine = client.readLine();
			} catch (SocketTimeoutException e) {
				break;
			}
			
			if (inputLine == null) {
				break;
			}
			
			lineSegmenter.segment(inputLine);

			if (map.containsKey(lineSegmenter.getType())) {
				map.get(lineSegmenter.getType()).performAction(client, this, lineSegmenter);
			}
			
			if (!lineSegmenter.getType().equals("PRIVMSG")) {
				continue;
			}
			
			for (Trigger t : triggerList) {
				t.updateVariables(nickName, lineSegmenter.getSender(), lineSegmenter.getReceiver(), lineSegmenter.getMessage());
				if (t.triggers(lineSegmenter.getMessage())) {
					if (!lineSegmenter.getReceiver().equals(nickName)) {
						t.updateVariables(nickName, lineSegmenter.getSender(), lineSegmenter.getReceiver(), lineSegmenter.getMessage());
					} else {
						t.updateVariables(nickName, lineSegmenter.getSender(), lineSegmenter.getReceiver(), lineSegmenter.getMessage());
					}
					client.write(t.response());
					break;
				}
			}
		}
		System.out.println("NOT CONNECTED");
		connect();
	}
	
	public String getNickName() {
		return nickName;
	}
	
	public void setNickName(String nickName) {
		this.nickName = nickName;
	}
}
